package com.gzdh.dishrecognition.ui.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.StringUtils;
import com.greendao.dao.OrdersEntityDao;
import com.gzdh.dishrecognition.AppContext;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.entity.OrdersEntity;
import com.gzdh.dishrecognition.ui.adapter.UnOnLineOrderAdapter;
import com.gzdh.dishrecognition.ui.base.BaseMVCActivity;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class UnOnLineActivity extends BaseMVCActivity {

    private RecyclerView recyclerView;

    private OrdersEntityDao ordersEntityDao;

    private UnOnLineOrderAdapter unOnLineOrderAdapter;

    private EditText nameEditText;

    private Spinner stateSpinner;

    private TextView checkTv;

    private TextView totalPriceTv;

    private TextView startTimeTv;

    private TextView endTimeTv;

    private Integer status;

    public static void start(Context context) {
        context.startActivity(new Intent(context, UnOnLineActivity.class));

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_unonline;
    }

    @Override
    protected void initView() {
        findViewById(R.id.backBut).setOnClickListener(view -> {
            finish();
        });
        ordersEntityDao = AppContext.getInstance().getDaoSession().getOrdersEntityDao();
        recyclerView = findViewById(R.id.recyclerView);
        stateSpinner = findViewById(R.id.stateSpinner);
        startTimeTv = findViewById(R.id.startTimeTv);
        startTimeTv.setText(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()));
        endTimeTv = findViewById(R.id.endTimeTv);
        endTimeTv.setText(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()));
        nameEditText = findViewById(R.id.nameEdit);
        nameEditText.setFocusable(false);
        nameEditText.setFocusableInTouchMode(false);
        checkTv = findViewById(R.id.checkBut);
        totalPriceTv = findViewById(R.id.total_price);
        unOnLineOrderAdapter = new UnOnLineOrderAdapter(mActivity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(unOnLineOrderAdapter);
        stateSpinner.setPrompt("请选择状态");
        List<Type> list = new ArrayList<>();
        list.add(new Type("全部", null));
        list.add(new Type("已上传", 1));
        list.add(new Type("未上传", 0));
        ArrayAdapter<Type> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
        stateSpinner.setAdapter(adapter);
        stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                Type type = (Type) adapterView.getItemAtPosition(position);
                status = type.getType();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    protected void initData() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        startTimeTv.setOnClickListener(view -> {
            Calendar calendar = Calendar.getInstance(); // 获取当前时间 — 年、月、日
            int year = calendar.get(Calendar.YEAR); // 得到当前年
            int month = calendar.get(Calendar.MONTH); // 得到当前月
            final int day = calendar.get(Calendar.DAY_OF_MONTH); // 得到当前日
            // 日期选择对话框
            new DatePickerDialog(UnOnLineActivity.this, (v, y, m, d) -> {
                String selectMonth = String.format(Locale.CHINA,"%02d", m + 1);
                String selectDay = String.format(Locale.CHINA, "%02d", d);
                startTimeTv.setText(String.format("%s-%s-%s", y, selectMonth, selectDay));
            }, year, month, day).show(); // 弹出日历对话框时，默认显示 年，月，日
        });
        endTimeTv.setOnClickListener(view -> {
            Calendar calendar = Calendar.getInstance(); // 获取当前时间 — 年、月、日
            int year = calendar.get(Calendar.YEAR); // 得到当前年
            int month = calendar.get(Calendar.MONTH); // 得到当前月
            final int day = calendar.get(Calendar.DAY_OF_MONTH); // 得到当前日
            // 日期选择对话框
            new DatePickerDialog(UnOnLineActivity.this, (v, y, m, d) -> {
                String selectMonth = String.format(Locale.CHINA,"%02d", m + 1);
                String selectDay = String.format(Locale.CHINA, "%02d", d);
                endTimeTv.setText(String.format("%s-%s-%s", y, selectMonth, selectDay));
            }, year, month, day).show(); // 弹出日历对话框时，默认显示 年，月，日
        });
        checkTv.setOnClickListener(view -> {
            QueryBuilder<OrdersEntity> queryBuilder = ordersEntityDao.queryBuilder();
            String start = startTimeTv.getText().toString();
            if(!StringUtils.isTrimEmpty(start)) {
                Date startTime;
                try {
                    startTime = dateFormat.parse(start + " 00:00:00");
                } catch (ParseException e) {
                    startTime = new Date();
                }
                queryBuilder.where(OrdersEntityDao.Properties.CreateTime.ge(startTime));
            }
            String end = endTimeTv.getText().toString();
            if(!StringUtils.isTrimEmpty(end)) {
                Date endTime;
                try {
                    endTime = dateFormat.parse(end + " 23:59:59");
                } catch (ParseException e) {
                    endTime = new Date();
                }
                queryBuilder.where(OrdersEntityDao.Properties.CreateTime.le(endTime));
            }
            String name = nameEditText.getText().toString();
            if(!StringUtils.isTrimEmpty(name)) {
                queryBuilder.where(OrdersEntityDao.Properties.Name.like("%" + name + "%"));
            }
            if(status != null) {
                queryBuilder.where(OrdersEntityDao.Properties.UpLoad.eq(status));
            }
            List<OrdersEntity> ordersEntityList = queryBuilder.list();
            ordersEntityList.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
            unOnLineOrderAdapter.setList(ordersEntityList);
            totalPriceTv.setText(unOnLineOrderAdapter.getTotalPrice());
        });
        checkTv.performClick(); //初始化时自动点击一次
        new Thread(() -> {
            try {
                Thread.sleep(500);
                runOnUiThread(() -> {
                    nameEditText.setFocusable(true);
                    nameEditText.setFocusableInTouchMode(true);
                });
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    @Override
    protected void dissmissPresnetation() {

    }


    //隐藏软键盘
    //在activity里面重写  dispatchTouchEvent
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
// 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    /**
     * 是否隐藏键盘
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = {0, 0};
//获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    public static class Type implements Serializable {

        public Type(String name, Integer type) {
            this.name = name;
            this.type = type;
        }

        private static final long serialVersionUID = 1L;

        private String name;

        private Integer type;


        public static long getSerialVersionUID() {
            return serialVersionUID;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getType() {
            return type;
        }

        public void setType(Integer type) {
            this.type = type;
        }

        @Override
        public String toString() {
            return name;
        }
    }

}
